<script setup lang="ts">
import RoomStatus from "./components/RoomStatus.vue";
import RoomAction from "./components/RoomAction.vue";
import RoomMessage from "./components/RoomMessage.vue";
import { nextTick, onMounted, onUnmounted, provide, ref } from "vue";
import { useRoute } from "vue-router";
import { io } from "socket.io-client";
import type { Socket } from "socket.io-client";
import { baseURL } from "@/utils/request";
import useStore from "@/stores";
import type { Message, TimeMessages } from "@/types/room";
import type { ConsultOrderItem, Image } from "@/types/consult";
import { getConsultOrderDetail } from "@/services/consult";
import { MsgType, OrderType } from "@/enums";
let socket: Socket;
onUnmounted(() => {
  // 关闭连接
  socket.close();
});
const route = useRoute();
const { user } = useStore();
// 订单信息
const consult = ref<ConsultOrderItem>();
// 消息列表
const list = ref<Message[]>([]);
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string);
  consult.value = res.data;
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${user.user?.token}`,
    },
    query: {
      orderId: route.query.orderId,
    },
  });
  socket.on("chatMsgList", ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = [];
    data.forEach((item) => {
      // 1. 处理消息时间
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime,
      });
      // 2. 其它消息
      arr.push(...item.items);
    });
    // 追加到聊天消息列表
    list.value.unshift(...arr);
  });
  // 接收消息
  socket.on("receiveChatMsg", async (msg) => {
    list.value.push(msg);
    await nextTick();
    window.scrollTo(0, document.body.scrollHeight);
  });
  socket.on("error", (event) => {
    // 错误异常消息
    console.log("error");
  });

  socket.on("disconnect", () => {
    // 已经断开连接
    console.log("disconnect");
  });
  // 3. 监听超级医生订单状态变更，更新订单状态（必须）
  socket.on("statusChange", async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string);
    consult.value = res.data;
  });
});
// 发送消息
const sendText = (text: string) => {
  socket.emit("sendChatMsg", {
    from: user.user?.id, //发送人
    to: consult.value?.docInfo?.id, //收消息人
    msgType: MsgType.MsgText, // 消息类型
    msg: { content: text }, // 消息内容
  });
};
// 发送图片
const sendImage = (img: Image) => {
  socket.emit("sendChatMsg", {
    from: user.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img },
  });
};
// -------------------评价
// 评价成功，修改评价消息状态和数据，切换卡片展示
const completeEva = (score: number) => {
  // 获取评价信息数据
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm);
  if (item) {
    item.msg.evaluateDoc = { score };
    item.msgType = MsgType.CardEva;
  }
};
provide("completeEva", completeEva);
provide("consult", consult);
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <!-- 1. 问诊状态-->
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <!-- 2. 问诊聊天列表消息 -->
    <room-message :list="list" />
    <!-- 3. 底部操作栏：发消息 -->
    <room-action
      @send-image="sendImage"
      @send-text="sendText"
      :disabled="consult?.status !== OrderType.ConsultChat"
    />
  </div>
</template>
<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
